//
//  CalendarView.m
//  Demo
//
//  Created by Zontonec on 17/1/11.
//  Copyright © 2017年 Zontonec. All rights reserved.
//

#import "CalendarView.h"
#import "CalendarCollectionViewCell.h"
#import "ConvertDate.h"

#define KMD_N(n) n * SCREENWIDTH / 375

#define KMD_RGBA(r,g,b,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:a]

//屏幕宽高
#define SCREENWIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREENHEIGHT [[UIScreen mainScreen] bounds].size.height

@interface CalendarView ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic , copy)NSString * selectedDate;//保存点击的日期来改变cell背景色 日期格式为20160101
@property(nonatomic,copy)NSString *aid; // 选中的Aid;

@property(retain,nonatomic)NSDate *currentDate; //当前日期

@property (nonatomic , assign)NSInteger daysNum;    //日
@property (nonatomic , assign)NSInteger monthsNum;//月份
@property (nonatomic , assign)NSInteger yearsNum;//年份

@property (nonatomic , assign)NSInteger days;       //某个月天数
@property (nonatomic , assign)NSInteger firsrtDay;//某年某月第一天星期几

@property (nonatomic , assign)NSInteger linesNum;//占几行

@property (nonatomic , strong)UICollectionView * calendarCollectionView;//日历CollectionView

@property (nonatomic , strong)NSArray * dataArr ;//保存初始化方法1传进来的数据

@property (nonatomic , strong)NSArray * dataDictArr ;//保存初始化方法2传进来的数据

@property (nonatomic , strong)NSArray * colorArr ;//日历背景色、当天的日期背景色、选中日期背景色

@property (nonatomic , strong)UIColor * dateColor;//有数据的日期背景色

@property (nonatomic , assign)NSInteger textOrBack;//1为数字改变颜色，2为背景改变颜色(边框)，3为背景整体改变颜色

/** 上月天数 */
@property(nonatomic, assign) NSInteger lastMonthDays;
/** 下月显示的日期 */
@property(nonatomic, assign) NSInteger nxetMonthDays;

@end

@implementation CalendarView

static NSString * const ID = @"cell";
#pragma mark - 初始化方法 -
-(instancetype)initWithFrame:(CGRect)frame colorArr:(NSArray *)arr textOrBackGround:(NSInteger)textOrBack clickDateBlock:(SendDateBlock)sendDateBlock {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        [self setBackgroundColor:[UIColor whiteColor]];
        
        self.textOrBack = textOrBack ;
        
        self.colorArr = [NSArray arrayWithArray:arr];
        
        self.currentDate = [NSDate date];
        
        //获取当前日期，以及年、月、日数字
        [self setupCurrentDate];
        
        //获取某月天数、获取第一天周几、获取日历有几行
        [self setUpCalendar];
        
        //在日历行显示的上个月灰色的天数
        NSArray * lastMonthArr = [self currentMonthCutWithYear:self.yearsNum month:self.monthsNum];
        
        self.lastMonthDays = [self numberOfDaysInYears:[lastMonthArr[0] integerValue] month:[lastMonthArr[1] integerValue]];
        
        //在日历上显示的下个月的数字
        self.nxetMonthDays = 1 ;
        
        [self setUpWeek];
        
        [self addSubview:self.calendarCollectionView];
    
        //一定要设置，不然Block无法回调;
        self.sendDateBlock = sendDateBlock;
    }
    return self ;
}

#pragma mark - 本月月份+1 -
-(NSArray * )currentMonthAddWithYear:(NSInteger )year month:(NSInteger )month{
    
    if (month + 1 > 12) {
        
        year  ++ ;
        month = 1;
    }
    else{
        
        month ++ ;
    }
    return @[[NSNumber numberWithInteger:year],[NSNumber numberWithInteger:month]];
}
#pragma mark - 本月月份-1 -
-(NSArray * )currentMonthCutWithYear:(NSInteger )year month:(NSInteger )month{
    
    if (month - 1 < 1) {
        
        year  -- ;
        month = 12;
    }
    else{
        
        month -- ;
    }
    return @[[NSNumber numberWithInteger:year],[NSNumber numberWithInteger:month]];
}

-(void)setUpWeek{
    
    //周一-----周日
    CGFloat labelWidth = SCREENWIDTH / 7 ;
    
    NSArray * weekArr = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    
    UIView * weekView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 30)];
    
    [weekView setBackgroundColor:KMD_RGBA(230, 230, 230, 1)];
    
    for (NSInteger i = 0 ; i < 7 ; i ++ ) {
        
        UILabel * weekdaysLabel = [[UILabel alloc]initWithFrame:CGRectMake(i * labelWidth, 0, labelWidth, 30)];
        
        [weekdaysLabel setText:weekArr[i]];
        
        [weekdaysLabel setFont:[UIFont systemFontOfSize:12]];
        
        [weekdaysLabel setBackgroundColor:KMD_RGBA(230, 230, 230, 1)];
        
        [weekdaysLabel setTextColor:KMD_RGBA(51, 51, 51, 1)];
        
        [weekdaysLabel setTextAlignment:NSTextAlignmentCenter];
        
        [weekView addSubview:weekdaysLabel];
    }
    [self addSubview:weekView];
}
#pragma mark - 懒加载初始化calendarCollectionView -
-(UICollectionView *)calendarCollectionView{
    
    if (!_calendarCollectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        [layout setItemSize:CGSizeMake(KMD_N((375 - 8)/7), KMD_N((375 - 8)/7))];
        
        layout.minimumInteritemSpacing = 1;
        
        layout.minimumLineSpacing =1;
        
        [layout setSectionInset:UIEdgeInsetsMake(1, 1, 1, 1)];
        
        _calendarCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 30, SCREENWIDTH, KMD_N(320)) collectionViewLayout:layout];
        
        [_calendarCollectionView setDelegate:self];
        
        [_calendarCollectionView setDataSource:self];
        
        [_calendarCollectionView setBackgroundColor:self.colorArr.count > 0?self.colorArr[0]:[UIColor greenColor]];
        
        [_calendarCollectionView setBackgroundColor:KMD_RGBA(240, 240, 240, 1)];
        
        [_calendarCollectionView registerClass:[CalendarCollectionViewCell class] forCellWithReuseIdentifier:ID];
    }
    return _calendarCollectionView ;
}
#pragma mark - 设置CollectionView -
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 6 * 7 ;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
     [cell.CalendarDateLabel setText:[NSString stringWithFormat:@"%ld",indexPath.row - self.firsrtDay+1]];
    [cell.start_time setText:@""];
    [cell.end_time setText:@""];
    [cell setBackgroundColor:[UIColor whiteColor]];
    [cell.CalendarDateLabel setTextColor:[UIColor blackColor]];
    
    if (indexPath.row < self.firsrtDay ) {
        
        //这个月第一天之前的那些cell
        [cell.CalendarDateLabel setText:nil];
        
        [cell.CalendarDateLabel setBackgroundColor:[UIColor whiteColor]];
        
        [cell setBackgroundColor:[UIColor whiteColor]];
        
        [cell.CalendarDateLabel setTextColor:KMD_RGBA(230, 230, 230, 1)];
        
        [cell.CalendarDateLabel setText:[NSString stringWithFormat:@"%ld",self.lastMonthDays - self.firsrtDay + indexPath.row+ 1]];
        
    } else if (indexPath.row < self.firsrtDay + self.days){
        //重载方法1有数据的日期
        if ([self.dataArr count] > 0) {
            NSString * date = [ConvertDate ConvertDateWithYear:self.yearsNum months:self.monthsNum day:indexPath.row - self.firsrtDay+1] ;

            NSLog(@"%@",date);

            NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
            [dateFormat setDateFormat:@"yyyy-M-d"];//设定时间格式,这里可以设置成自己需要的格式
            NSDate *Mydate =[dateFormat dateFromString:date];

            NSDateFormatter* dateFormat1 = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象

            [dateFormat1 setDateFormat:@"yyyyMd"];//设定时间格式,这里可以设置成自己需要的格式
            　NSString *currentDateStr = [dateFormat1 stringFromDate:Mydate];

            NSString *currentDateStr1 = [currentDateStr stringByReplacingOccurrencesOfString:@"-" withString:@""];

            for (NSDictionary * time in self.dataArr) {
                NSLog(@"%@",time);

                if ([currentDateStr1 isEqualToString:time[@"ymd"]]){
                    [cell setBackgroundColor:[UIColor whiteColor]];
                    //[cell.CalendarDateLabel setText:@""];
                    [cell.CalendarDateLabel setTextColor:KMD_RGBA(230, 230, 230, 1)];
                    [cell.start_time setText:time[@"start_time"]];
                    [cell.end_time setText:time[@"end_time"]];
                    [cell.start_time setTextColor:KMD_RGBA(235, 97, 0, 1)];
                    [cell.end_time setTextColor:KMD_RGBA(235, 97, 0, 1)];
                    break ;
                }
            }
        }
        //今天的日期的颜色
        if ([[ConvertDate ConvertDateWithYear:self.yearsNum months:self.monthsNum day:indexPath.row - self.firsrtDay+1] isEqualToString:[self NSDateToNSString:[NSDate date]]]){
            [cell.CalendarDateLabel setBackgroundColor:[UIColor whiteColor]];
            [cell.CalendarDateLabel setTextColor:KMD_RGBA(235, 97, 0, 1)];
        }
        
    }else{
        
        [cell setBackgroundColor:[UIColor whiteColor]];
        
        [cell.CalendarDateLabel setText:[NSString stringWithFormat:@"%ld",self.nxetMonthDays]];
        
        [cell.CalendarDateLabel setBackgroundColor:[UIColor whiteColor]];
        
        [cell.CalendarDateLabel setTextColor:KMD_RGBA(230, 230, 230, 1)];
        
        self.nxetMonthDays ++ ;
    }
    
    //改变点击的cell的背景色
    if (self.selectedDate) {

    }
    return cell;
}

////字符串转日期格式
//- (NSDate *)stringToDate:(NSString *)dateString withDateFormat:(NSString *)format
//{
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:format];
//
//    NSDate *date = [dateFormatter dateFromString:dateString];
//    return [self worldTimeToChina:date];
//}
//
////将世界时间转化为中国区时间
//- (NSDate *)worldTimeToChinaTime:(NSDate *)date
//{
//    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
//    NSInteger interval = [timeZone secondsFromGMTForDate:date];
//    NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
//    return localeDate;
//}



#pragma mark - 点击事件 -
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    //点击的cell下标不能小于本月第一天，也不能超过本月最后一天
    if (indexPath.row >= self.firsrtDay && indexPath.row < self.firsrtDay+self.days)
    {
        //点击的cell改变颜色
        self.selectedDate = [ConvertDate ConvertDateWithYear:self.yearsNum months:self.monthsNum day:indexPath.row- self.firsrtDay+1];

        if ([self.selectedDate floatValue]<[[self NSDateToNSString:[NSDate date]] floatValue])
        {
            NSLog(@"%@ %@",self.selectedDate,[self NSDateToNSString:[NSDate date]]);

            return;
        }

        int booldate = [self compareOneDay:self.selectedDate withAnotherDay:[self NSDateToNSString:[NSDate date]]];

        if (booldate ==1)
        {

        }else if(booldate == 0)
        {

        }else
        {
            return;
        }

        if (self.sendDateBlock)
        {
            self.sendDateBlock(self.selectedDate,indexPath);
        }
    }

    self.nxetMonthDays = 1 ;
}


- (int)compareOneDay:(NSString *)oneDay withAnotherDay:(NSString *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
//    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
//    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDay];
    NSDate *dateB = [dateFormatter dateFromString:anotherDay];

    NSComparisonResult result = [dateA compare:dateB];



    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;

}



#pragma mark - 传进来一个时间重载CollectionView -
-(void)reloadCalendarViewWithDate:(NSString *)date{
    
    
    NSMutableArray * dateArr = [NSMutableArray arrayWithArray:[self cutString:date bySymbol:@"-"]];
    
    self.yearsNum = [dateArr[0] integerValue];
    
    self.monthsNum = [dateArr[1] integerValue];
    
    self.daysNum = [dateArr[2] integerValue];
    
    self.nxetMonthDays = 1 ;
    
    //在日历行显示的上个月灰色的天数
    NSArray * lastMonthArr = [self currentMonthCutWithYear:self.yearsNum month:self.monthsNum];
    
    self.lastMonthDays = [self numberOfDaysInYears:[lastMonthArr[0] integerValue] month:[lastMonthArr[1] integerValue]];
    
    [self setUpCalendar];//获取某月天数、获取第一天周几、获取日历有几行
    
    [self.calendarCollectionView reloadData];
}
#pragma mark - 重载方法1: -
-(void)reloadCalendarViewWithArr:(NSArray *)arr color:(UIColor *)dateColor{
    //只有一种数据要显示背景色的时候用这个重载方法，比如只显示有服药的日期时可以用，下面cellForItemAtIndexPath里面有数据的日期需要修改
    self.dataArr = [NSArray arrayWithArray:arr];
    
    self.dateColor = dateColor ;
    
    self.nxetMonthDays = 1 ;
    
    //在日历行显示的上个月灰色的天数
    NSArray * lastMonthArr = [self currentMonthCutWithYear:self.yearsNum month:self.monthsNum];
    
    self.lastMonthDays = [self numberOfDaysInYears:[lastMonthArr[0] integerValue] month:[lastMonthArr[1] integerValue]];
    
    [self.calendarCollectionView reloadData];
}
#pragma mark - 获取年月日 - 获取当前日期，以及年、月、日数字
-(void)setupCurrentDate{
    
    NSString * currentStr = [self NSDateToNSString:self.currentDate];//获取当前时间，日期
    
    NSMutableArray * dateArr = [NSMutableArray arrayWithArray:[self cutString:currentStr bySymbol:@"-"]];
    
    self.yearsNum = [dateArr[0] integerValue];
    
    self.monthsNum = [dateArr[1] integerValue];
    
    self.daysNum = [dateArr[2] integerValue];
}
-(NSDate *)NSStringToNSDateWithString:(NSString *)str{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *date = [dateFormatter dateFromString:str];
    
    return date ;
}
#pragma mark - 获取某月天数、获取第一天周几、获取日历有几行 -
-(void)setUpCalendar{
    
    //根据年月计算这个月有多少天
    self.days = [self numberOfDaysInYears:self.yearsNum month:self.monthsNum];
    
    //获取第一天星期几
    self.firsrtDay = [self GetTheWeekOfDayByYera:self.yearsNum andByMonth:self.monthsNum];
    
    //第一周的天数    7 - self.firsrtDay
    //占几行                   占得满周                                    最后剩下的天数
    self.linesNum =1+ (self.days - ( 7 - self.firsrtDay )) / 7 +( ( self.days - ( 7 - self.firsrtDay ) )%7 > 0? + 1 : + 0 );
    
    if (self.firsrtDay == 7)
        
        self.linesNum -- ;
}
#pragma mark - 设置日历 -----  这个月有多少天 -
- (NSUInteger)numberOfDaysInYears:(NSInteger )year month:(NSInteger )month{
    
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
        return 31 ;
    
    if((month == 4) || (month == 6) || (month == 9) || (month == 11))
        return 30;
    
    if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3))
    {
        return 28;
    }
    
    if(year % 400 == 0)
        return 29;
    
    if(year % 100 == 0)
        return 28;
    
    return 29;
}
#pragma mark - 设置日历 ----- 确定当前月的第一天星期几 -> 当前月份的第一周有几天 -
-(NSInteger)GetTheWeekOfDayByYera:(NSInteger )year andByMonth:(NSInteger )month{
    NSInteger sum = 0;
    for(NSInteger i = 1;i<month;i++){
        sum+=[self getDays:year and:i];
    }
    NSInteger nedDay = sum+1;
    
    return ((year-1)+(year-1)/4 -(year/100)+(year/400)+nedDay)%7;
}
-(NSInteger)getDays:(NSInteger )year and:(NSInteger)day{
    
    NSInteger times [] = {31,28,31,30,31,30,31,31,30,31,30,31};
    
    if ((year%4==0&&year%100!=0)||year%400==0) {
        
        times[1] = 29;
    }
    return (times[day-1]);
}
#pragma mark - 设置日历 ----- NSDate 转 NSString -
-(NSString *)NSDateToNSString:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    return dateString;
}
#pragma mark - 字符串分割 -
-(NSArray *)cutString:(NSString *)str bySymbol:(NSString *)symbol {
    
    NSArray * cut ;
    
    cut = [str componentsSeparatedByString:symbol];
    
    return cut;
}
@end
